<?php
/*
 * @Author: SanQian
 * @Date: 2021-08-27 16:05:43
 * @LastEditTime: 2021-09-07 10:31:31
 * @LastEditors: SanQian
 * @Description:
 * @FilePath: /tools_php_gaode/src/GaodeBasic.php
 *
 */
namespace Zhaohangyang\ToolsPhpGaode;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ServerException;
use Zhaohangyang\ToolsPhpGaode\Cache\GaodeCache;

// use GuzzleHttp\Exception\ServerException;
// use GuzzleHttp\Pool;
// use GuzzleHttp\Psr7\Request;
/**
 * 高德基础类
 */
class GaodeBasic
{
    public $apiClient;
    public $cache;
    public $gaodeConfig = [
        // -- cache_path
    ];

    public $standardConfig = [
        // 高德应用key
        'key'     => '',
        // api基础域名
        'api_url' => '',
    ];

    public function __construct($gaode_config)
    {
        $this->verifyConfig($gaode_config);
        $this->gaodeConfig = $gaode_config;

        $this->cache     = new GaodeCache($this->gaodeConfig['cache_path'] ?? '');
        $this->apiClient = $this->setApiClient($this->gaodeConfig['api_url']);
    }

    public function verifyConfig($gaode_config)
    {
        $diff_keys = array_diff_key($this->standardConfig, $gaode_config);

        if (!empty($diff_keys)) {
            throw new \Exception("配置参数不全，缺少:" . implode(",", array_keys($diff_keys)), 1);
        }
    }

    public function addStandardConfig($key, $value = '')
    {
        $this->standardConfig[$key] = $value;
    }

    public function setApiClient($api_url)
    {
        $this->apiClient = new Client([
            'base_uri'    => $api_url ?: $this->gaodeConfig['api_url'],
            'timeout'     => 600,
            'verify'      => false,
            'http_errors' => false,
        ]);

        return $this->apiClient;
    }

    public function getApiClient($api_url)
    {
        return $this->apiClient ?: $this->setApiClient($api_url);
    }

    /**
     * 发送请求，并返回结果
     *
     * @param \GuzzleHttp\Psr7\Request $request
     * @param string $interface_type
     * @return void
     */
    public function requestJsonSync(\GuzzleHttp\Psr7\Request $request)
    {
        try {
            $response = $this->apiClient->send($request);
        } catch (ServerException $e) {
            $response = $e->getResponse();
        }

        return json_decode($response->getBody(), true);
    }

}
